package com.mmlc.meimei.lichengkongjian.classify;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.androidnetframe.httputil.BaseRequestFilterLayer;
import com.androidnetframe.requestbean.BaseResponseBean;
import com.androidnetframe.responsejavabean.RequestError;
import com.androidnetframe.utils.LogUtils;
import com.easemob.helpdeskdemo.Constant;
import com.mmlc.businessutils.MyShareUtils;
import com.mmlc.inter.InterActivity;
import com.mmlc.meimei.lichengkongjian.App;
import com.mmlc.meimei.lichengkongjian.R;
import com.mmlc.meimei.lichengkongjian.customview.BanViewPager;
import com.mmlc.meimei.lichengkongjian.customview.CustomExpandableListView;
import com.mmlc.meimei.lichengkongjian.customview.SimpleTagImageView;
import com.mmlc.meimei.lichengkongjian.customview.SlideDetailsLayout;
import com.mmlc.meimei.lichengkongjian.home.WebViewActivity;
import com.mmlc.meimei.lichengkongjian.mine.LoginActivity;
import com.mmlc.meimei.lichengkongjian.shoppingbag.ShoppingCartActivity;
import com.mmlc.network.filter.ApplyShelfRequestFilter;
import com.mmlc.network.filter.FastBuyNoticeRequestFilter;
import com.mmlc.network.filter.GoodsCollectRequestFilter;
import com.mmlc.network.filter.GoodsDetailRequestFilter;
import com.mmlc.network.filter.JoinCartRequestFilter;
import com.mmlc.network.responsebean.FastBuyGoodsDetailResponseBean;
import com.mmlc.network.responsebean.GoodsDetailBaseResponseBean;
import com.mmlc.utils.FastGoodsDetailUtils;
import com.mmlc.utils.ToastUtils;
import com.mmlc.utils.ViewUtils;
import com.mmlc.utils.XUtils;
import com.mmlc.widget.FastBuyBanner;
import com.squareup.picasso.Transformation;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.xutils.common.util.LogUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2016/12/5.
 */
public class FastGoodsDetailActivity extends InterActivity implements View.OnClickListener, SlideDetailsLayout.OnSlideDetailsListener {

    @InjectView(R.id.tv_titlesecond)
    TextView tvTitlesecond;
    @InjectView(R.id.tv_total)
    TextView tvTotal;
    @InjectView(R.id.tv_market_price)
    TextView tvMarketPrice;
    @InjectView(R.id.tv_needtime)
    TextView tvNeedtime;
    @InjectView(R.id.tv_day)
    TextView tvDay;
    @InjectView(R.id.tv_hour)
    TextView tvHour;
    @InjectView(R.id.tv_minute)
    TextView tvMinute;
    @InjectView(R.id.tv_second)
    TextView tvSecond;
    @InjectView(R.id.ps_progressBar)
    ProgressBar psProgressBar;
    @InjectView(R.id.tv_atleastnum)
    TextView tvAtleastnum;
    @InjectView(R.id.tv_sellnum)
    TextView tvSellnum;
    @InjectView(R.id.cdl_content)
    CoordinatorLayout cdl_content;
    @InjectView(R.id.sv_switch)
    SlideDetailsLayout sv_switch;
    @InjectView(R.id.ll_pull_up)
    LinearLayout ll_pull_up;
    @InjectView(R.id.sv_goods_info)
    ScrollView sv_goods_info;
    @InjectView(R.id.iv_back)
    ImageView ivBack;
    @InjectView(R.id.info_banner)
    FastBuyBanner infoBanner;
    @InjectView(R.id.tv_titlefirst)
    TextView tvTitlefirst;
    @InjectView(R.id.iv_iclike)
    ImageView ivIclike;
    @InjectView(R.id.tv_bag_count)
    TextView tv_bag_count;
    @InjectView(R.id.iv_shopping_bag)
    ImageView ivShoppingBag;
    @InjectView(R.id.rl_shopping_bag)
    RelativeLayout rlShoppingBag;
    @InjectView(R.id.iv_service)
    ImageView ivService;
    @InjectView(R.id.tv_gopay)
    TextView tvGopay;
    @InjectView(R.id.ll_nav_bottom)
    LinearLayout llNavBottom;
    @InjectView(R.id.tv_replace)
    TextView tvReplace;
    @InjectView(R.id.ll_replace)
    LinearLayout llReplace;
    @InjectView(R.id.iv_share)
    ImageView ivShare;
    @InjectView(R.id.rl_nav_bottom)
    RelativeLayout rl_nav_bottom;
    @InjectView(R.id.tv_currentprogress)
    TextView tv_currentprogress;
    @InjectView(R.id.ll_promise)
    LinearLayout ll_promise;
    @InjectView(R.id.expand_lv_main)
    CustomExpandableListView mExpandableListView;
    @InjectView(R.id.tv_times)
    SimpleTagImageView tv_times;
    @InjectView(R.id.ll_notstart)
    RelativeLayout ll_notstart;
    @InjectView(R.id.tv_nostart)
    TextView tv_nostart;
    @InjectView(R.id.tv_typetitle)
    TextView tv_typetitle;
    @InjectView(R.id.iv_divider)
    ImageView iv_divider;
    @InjectView(R.id.rl_progress)
    RelativeLayout rl_progress;
    @InjectView(R.id.ll_counttime)
    LinearLayout ll_counttime;
    //    @InjectView(R.id.iv_product)
//    ImageView iv_product;
    @InjectView(R.id.ll_product)
    LinearLayout  ll_product;
    @InjectView(R.id.view_line)
    View view_line;
    @InjectView(R.id.ll_status)
    LinearLayout ll_status;
    @InjectView(R.id.tv_productone)
    TextView tv_productone;
    @InjectView(R.id.tv_producttwo)
    TextView tv_producttwo;
    @InjectView(R.id.tv_productinfo)
    TextView tv_productinfo;
    @InjectView(R.id.tv_title)
    TextView tv_title;
    @InjectView(R.id.tv_scan)
    TextView tv_scan;
    @InjectView(R.id.layout_error)
    LinearLayout layout_error;
    @InjectView(R.id.rl_title)
    RelativeLayout rl_title;
    @InjectView(R.id.tv_info)
    TextView tv_info;
    @InjectView(R.id.rootView)
    RelativeLayout rootView;
    @InjectView(R.id.line_cut)
    View line_cut;
    @InjectView(R.id.tv_addCart)
    TextView tv_addCart;
    @InjectView(R.id.tv_barcode)
    TextView tv_barcode;

    @Override
    protected int initContentView() {
        return R.layout.activity_fastgoodsdetail;
    }


    String id,gdid;
    List<Fragment> fragmentList;
    List<String> mTitleList;
    FastGoodsDetailFragment fragment;

    WebView dialog_web_size;
    int navIndex = -1;
    FastBuyGoodsDetailResponseBean goodsDetail;
    GoodsDetailBaseResponseBean.DataBean goodsDetailData;

    public int loc = 0;
    public Timer timer = new Timer();
    public long time = 0;
    public String scan;

    @Override
    protected void initView() {
        ButterKnife.inject(FastGoodsDetailActivity.this);
        Intent intent = getIntent();
        id = intent.getStringExtra("id");
        scan = intent.getStringExtra("scan");
        rlShoppingBag.setOnClickListener(this);
        tvGopay.setOnClickListener(this);
        ll_pull_up.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        ivShare.setOnClickListener(this);
        ivIclike.setOnClickListener(this);
        ivService.setOnClickListener(this);

    }

//    public  void getSaleNum(){
//        GoodsDetailRequestFilter filter = new GoodsDetailRequestFilter(activity);
//        filter.requestBean.goods_id = id;
//        filter.offerErrorParams((ViewGroup) ViewUtils.getView(activity, R.id.rootView));
//        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<FastBuyGoodsDetailResponseBean>() {
//            @Override
//            public void onSuccess(FastBuyGoodsDetailResponseBean result) {
//                if(result!=null){
//                    if(!TextUtils.isEmpty((result.getData().getStock()))) {
//                        //设置进度值
//                        progressBarComplete.setMax(Integer.parseInt(result.getData().getStock()));
//                        progressBarComplete.setProgress(Integer.parseInt(result.getData().getSale_num()));
//                    }
//                    statusInfo.clear();
//                    statusInfo.addAll(result.getData().getStatus_info());
//                    adapter.notifyDataSetChanged();
//                    llStarting.setVisibility(View.GONE);
//                    llEnd.setVisibility(View.VISIBLE);
//                }else{
//                    ToastUtils.showToast("数据错误");
//                }
//
//            }
//
//            @Override
//            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
//                ToastUtils.showToast(serverError.mess);
//            }
//        });
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
        if(null != buyDialog){
            buyDialog.dismiss();
        }
        if(null !=dialog_info){
            dialog_info.dismiss();
        }
    }



    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    int day = (int) (time / 3600L / 24L);
                    int hour = (int) ((time - day * 24L * 3600L) / 3600L);
                    int minute = (int) (time / 60L) - day * 24 * 60 - hour * 60;
                    int seconds = (int) (time - day * 24 * 3600 - hour * 3600 - minute * 60);
                    if (day < 10) {
                        tvDay.setText("0" + day);
                    } else {
                        tvDay.setText(day + "");
                    }
                    if (hour < 10) {
                        tvHour.setText("0" + hour);
                    } else {
                        tvHour.setText(hour + "");
                    }
                    if (minute < 10) {
                        tvMinute.setText("0" + minute);
                    } else {
                        tvMinute.setText(minute + "");
                    }
                    if (seconds < 10) {
                        tvSecond.setText("0" + seconds);
                    } else {
                        tvSecond.setText(seconds + "");
                    }
                    if (time <= 0) {
                        timer.cancel();
//                        getSaleNum();
                    }
            }
        }
    };

    // 设置倒计时
    private void setCountdownTime(long timeleft) {
        time = timeleft;
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                time--;
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
            }
        };
        timer.schedule(task, 1000, 1000);
    }


    UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA share_media) {
            ToastUtils.showToast(share_media.toString());
        }

        @Override
        public void onError(SHARE_MEDIA share_media, Throwable throwable) {
            ToastUtils.showToast(share_media.toString());
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media) {
            ToastUtils.showToast(share_media.toString());
        }
    };

    /**
     * 分享
     */
   /* UMSocialService mController;*/
    UMShareAPI mShareAPI = null;
    private UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            Toast.makeText(getApplicationContext(), "Authorize succeed", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            Toast.makeText(getApplicationContext(), "Authorize fail", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            Toast.makeText(getApplicationContext(), "Authorize cancel", Toast.LENGTH_SHORT).show();
        }
    };

    private void showShare() {
        MyShareUtils.showShare(goodsDetail.getData().getGoods_name(),
                tvTotal.getText().toString(),
                goodsDetail.getData().getShare_url(),
                goodsDetail.getData().getImg_thumb()
        );
    }

    List<FastBuyGoodsDetailResponseBean.DataBean.TipsBean> tips;
    String h5_url;
    int event_type;
    String notice_id;
    @Override
    protected void initInfo() {

        GoodsDetailRequestFilter filter = new GoodsDetailRequestFilter(activity);
        filter.requestBean.goods_id = id;
        if(!TextUtils.isEmpty(scan)&&scan.equals("scan")){
            filter.requestBean.sku = getIntent().getStringExtra("sku");
        }
        filter.offerErrorParams(rootView);
        filter.isTransparence = true;
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<FastBuyGoodsDetailResponseBean>() {
            @Override
            public void onSuccess(FastBuyGoodsDetailResponseBean result) {
                if(result!=null ) {
                    if(result.getCode() == 0){
                        if (!TextUtils.isEmpty(scan) && scan.equals("scan")) {
                            tv_title.setText("码上购");
                        } else {
                            tv_title.setText("详情");
                        }
                        rl_nav_bottom.setVisibility(View.VISIBLE);
                    }else if(result != null && result.getCode()== 10000) {
                        if (!TextUtils.isEmpty(scan) && scan.equals("scan")) {
                            tv_title.setText("码上购");
                        } else {
                            tv_title.setText("详情");
                        }
                        if(App.user.getUserType()==0){
                            tv_scan.setText("返回");
                        }else{
                            tv_scan.setText("申请上架");
                        }
                        tv_info.setVisibility(View.VISIBLE);
                        tv_scan.setVisibility(View.VISIBLE);
                    }
                    rl_title.setVisibility(View.VISIBLE);
                    cdl_content.setVisibility(View.VISIBLE);
                    gdid = result.getData().getId()+"";
                    goodsDetail = result;
                    tips = new ArrayList<>();
                    tips = result.getData().getTips();
                    notice_id = result.getData().getId();
                    //设置期数
                    tv_times.setTagText("第"+result.getData().getBatch()+"期");
                    //初始化七天
                    initPromise();
                    //设置banner
                    if (result.getData().getGoods_album() != null && result.getData().getGoods_album().size() > 0) {
                        infoBanner.setDatas(result.getData().getGoods_album());

                    }
                    //装载商品详情介绍的webview
                    initViewPager(result);
                    getGoodsDetailBase(result.getData());
                    displayGoodsDetail(result.getData());

                    //获取活动时间
                    FastBuyGoodsDetailResponseBean.DataBean.EventInfoBean event_info = result.getData().getEvent_info();
                    event_type = event_info.getType();
                    //活动进行中
                    if(event_type == 2){
                        line_cut.setVisibility(View.VISIBLE);
                        tv_addCart.setVisibility(View.VISIBLE);
                        ll_counttime.setVisibility(View.VISIBLE);
                        view_line.setVisibility(View.VISIBLE);
                        if(!TextUtils.isEmpty(result.getData().getExpect_num()+"")){
                            //设置进度值
                            tvAtleastnum.setText(result.getData().getExpect_num()+"");
                            double rate = result.getData().getFinish_rate();
                            if(rate*10 % 10 == 0){
                                tv_currentprogress.setText((int)(rate * 10 / 10)+"%");
                            }else {
                                tv_currentprogress.setText(result.getData().getFinish_rate() + "%");
                            }
                        }
                        if((result.getData().getFinish_rate()/100)<1){
                            psProgressBar.setProgress((int)result.getData().getFinish_rate());
                        }else{
                            psProgressBar.setProgress(100);
                        }
                        tvSellnum.setText("已成功订购"+result.getData().getSale_num()+"件");
                        if(!TextUtils.isEmpty(event_info.getDesc())){
                            tv_typetitle.setText(event_info.getDesc());
                        }
                        //开启计时器
                        setCountdownTime(event_info.getTime());
                    }else {
                        line_cut.setVisibility(View.GONE);
                        tv_addCart.setVisibility(View.GONE);
                    }


                    //未进行，没有倒计时
                    if(event_type == 0){
                        if(event_info.getTime() == 0){
                            ll_notstart.setVisibility(View.VISIBLE);
                            tv_nostart.setText(event_info.getDesc());
                        }
                    }
                    //未进行，有倒计时
                    if( event_type == 1){
                        if(event_info.getTime()!=0){
                            view_line.setVisibility(View.VISIBLE);
                            ll_counttime.setVisibility(View.VISIBLE);
                            iv_divider.setVisibility(View.GONE);
                            rl_progress.setVisibility(View.GONE);
                            tv_currentprogress.setVisibility(View.GONE);
                            tvSellnum.setVisibility(View.GONE);
                            tv_typetitle.setText(event_info.getDesc());
                            setCountdownTime(event_info.getTime());
                        }
                    }

                    //按钮状态
                    tvGopay.setText(event_info.getDesc_button());


                    //初始化制造商
                    if(null != result.getData().getFactory_info()) {

                        ll_product.setVisibility(View.VISIBLE);
                        tv_productone.setText(result.getData().getFactory_info().getTitle());
                        tv_producttwo.setText(result.getData().getFactory_info().getSubtitle());
                        tv_productinfo.setText(result.getData().getFactory_info().getDesc());
//                        XUtils.image(iv_product, result.getData().getFactory_info().getImg(),XUtils.getImageOptionsBuilder().setImageScaleType(ImageView.ScaleType.CENTER_CROP).build());
//                        iv_product.setClickable(true);
//                        Picasso.with(context)
//                                .load(result.getData().getFactory_info().getImg())
//                                .noFade()
//                                .into(iv_product);
                        h5_url = result.getData().getFactory_info().getH5_url();
                    }

                    //初始化进展状态
                    groupInfo = new ArrayList<>();
                    groupInfo = result.getData().getStatus_info();
                    if(groupInfo.size()!=0){
                        ll_status.setVisibility(View.VISIBLE);
                        initStatus();
                    }
                } else{
                    rl_nav_bottom.setVisibility(View.GONE);
                    cdl_content.setVisibility(View.GONE);
                    ivShare.setVisibility(View.GONE);
                    ToastUtils.showToast("数据错误");
                }
            }
            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                rl_nav_bottom.setVisibility(View.GONE);
                ivShare.setVisibility(View.GONE);
                cdl_content.setVisibility(View.GONE);
                if(!TextUtils.isEmpty(scan) && scan.equals("scan") ) {
                    if(serverError.errCode.equals("2")){
                        layout_error.setVisibility(View.VISIBLE);
                    }
                }else{
                    ToastUtils.showToast(serverError.mess);
                }
            }
        });
    }

    //初始化包邮 七天
    LinearLayout.LayoutParams params;
    public  void initPromise(){
        for (int i = 0; i < tips.size(); i++) {
            params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            TextView textView = new TextView(this);
            textView.setText(tips.get(i).getName());
            textView.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_border_black));
            textView.setTextSize(13);
            if(i == 0){
                params.leftMargin = 20;
            }else{
                params.leftMargin = 13;
            }
            params.topMargin = 20;
            params.bottomMargin  = 20;
            ll_promise.addView(textView,params);
        }

        ll_promise.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initInfoDialog();
            }
        });


    }

    //初始化  进展状态信息
    List<FastBuyGoodsDetailResponseBean.DataBean.StatusInfoBean> groupInfo;
    ExpandAdapter adapter;
    public void initStatus() {
        LogUtils.e("213","213131");
        adapter = new ExpandAdapter();
        mExpandableListView.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        mExpandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition) {
                for (int i = 0; i < adapter.getGroupCount(); i++) {
                    if (groupPosition != i) {
                        mExpandableListView.collapseGroup(i);
                    }
                }
            }
        });
        mExpandableListView.expandGroup(0);
    }


    public class ExpandAdapter extends BaseExpandableListAdapter{


        @Override
        public int getGroupCount() {
            return groupInfo.size();
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return groupInfo.get(groupPosition).getInfo().size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return groupInfo.get(groupPosition);
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return groupInfo.get(groupPosition).getInfo().get(childPosition);
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            View view = convertView;
            GroupHolder holder = null;
            if(view == null){
                holder = new GroupHolder();
                view = LayoutInflater.from(FastGoodsDetailActivity.this).inflate(R.layout.group_item, null);
                holder.groupName = (TextView)view.findViewById(R.id.tv_count);
                holder.time = (TextView)view.findViewById(R.id.tv_time);
                holder.sell = (TextView)view.findViewById(R.id.tv_haveselled);
                holder.arrow = (ImageView)view.findViewById(R.id.iv_arrow);
                view.setTag(holder);
            }else{
                holder = (GroupHolder)view.getTag();
            }

            //判断是否已经打开列表
            if(isExpanded){
                holder.arrow.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_down));
            }else{
                holder.arrow.setBackgroundDrawable(getResources().getDrawable(R.drawable.next));
            }

            holder.groupName.setText("第"+groupInfo.get(groupPosition).getBatch_num()+"期");
            holder.time.setText(groupInfo.get(groupPosition).getTimeinfo()+"");
            holder.sell.setText("已售"+groupInfo.get(groupPosition).getSale_num());
            return view;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {

            View view = convertView;
            ChildHolder holder = null;
            if(view == null){
                holder = new ChildHolder();
                view = LayoutInflater.from(FastGoodsDetailActivity.this).inflate(R.layout.follow_child_item, null);
                holder.childName = (TextView)view.findViewById(R.id.tv_title);
                holder.time = (TextView) view.findViewById(R.id.tv_time);
                holder.iv_line = (ImageView) view.findViewById(R.id.iv_line);
                view.setTag(holder);
            }else{
                holder = (ChildHolder)view.getTag();
            }

            if(groupInfo.get(groupPosition).getInfo().get(childPosition).getIs_cur()==2){
                holder.childName.setTextColor(Color.parseColor("#52b269"));
                holder.childName.setTextSize(16);
            }else if(groupInfo.get(groupPosition).getInfo().get(childPosition).getIs_cur() == 0){
                holder.childName.setTextColor(Color.parseColor("#b2b2b2"));
                holder.childName.setTextSize(14);
            }else{
                holder.childName.setTextColor(Color.parseColor("#282a2b"));
                holder.childName.setTextSize(14);
            }

            holder.childName.setText(groupInfo.get(groupPosition).getInfo().get(childPosition).getDescription());
            holder.time.setText(groupInfo.get(groupPosition).getInfo().get(childPosition).getUpdate_time());
            if(childPosition == groupInfo.get(groupPosition).getInfo().size()-1){
                holder.iv_line.setVisibility(View.GONE);
            }else{
                holder.iv_line.setVisibility(View.VISIBLE);
            }

            return view;

        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return false;
        }

        class GroupHolder{
            public TextView groupName ,time,sell;
            public ImageView arrow;
        }

        class ChildHolder{
            public TextView childName,time;
            public ImageView iv_line;
        }


    }


    View infoView;
    TextView tv_complete;
    Dialog dialog_info;
    ListView ls_info;
    public  void initInfoDialog() {
        if (dialog_info == null) {
            infoView = getLayoutInflater().inflate(R.layout.dialog_info, null);
            infoView.setMinimumWidth(getResources().getDisplayMetrics().widthPixels);
            tv_complete = ViewUtils.getView(infoView, R.id.tv_complete);
            ls_info = ViewUtils.getView(infoView,R.id.ls_info);
            ls_info.setAdapter(new DialogAdapter());
            tv_complete.setOnClickListener(this);
            dialog_info = new Dialog(activity, R.style.BuyDialogStyle);
            dialog_info.setContentView(infoView);
            Window dialogWindow = dialog_info.getWindow();
            Display display = getWindowManager().getDefaultDisplay();
            WindowManager.LayoutParams lp = dialog_info.getWindow().getAttributes();
            lp.width = (int)(display.getWidth()); //设置宽度
            lp.height =(int)(display.getHeight()*0.7);
            dialog_info.getWindow().setAttributes(lp);
            dialogWindow.setGravity(Gravity.BOTTOM);
        }
        dialog_info.show();
    }



    //商品详情标签
    private void initViewPager(FastBuyGoodsDetailResponseBean result){
        mTabLayout = (TabLayout) findViewById(R.id.tay_home_tab_view);
        mViewPager = (BanViewPager) findViewById(R.id.tay_home_pager_view);
//        mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        setDetailData(result);
        PagerAdapter mAdapter = new PagerAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(mAdapter);
        mViewPager.setOffscreenPageLimit(3);
        mTabLayout.setupWithViewPager(mViewPager); //将TabLayout和ViewPager关联起来
    }

    //获取商品详情fragment
    public void setDetailData(FastBuyGoodsDetailResponseBean result) {

        if (null != result.getData().getTab_info()) {
            List<FastBuyGoodsDetailResponseBean.DataBean.TabInfoBean> tabinfo = result.getData().getTab_info();
            mTitleList = new ArrayList<>();
            fragmentList = new ArrayList<>();
            for (int i = 0; i < tabinfo.size(); i++) {
                //tab标签
                mTitleList.add(tabinfo.get(i).getName());
                mTabLayout.addTab(mTabLayout.newTab().setText(tabinfo.get(i).getName()));
                //fragment
                fragment = new FastGoodsDetailFragment();
                Bundle bundle = new Bundle();
                bundle.putString("type", tabinfo.get(i).getUrl());
                fragment.setArguments(bundle);
                fragmentList.add(fragment);
            }
        }else{
            return;
        }
    }

    public class PagerAdapter extends FragmentStatePagerAdapter {


        public PagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {

            return  fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mTitleList.size();
        }

        //用来设置tab的标题
        @Override
        public CharSequence getPageTitle(int position) {
            return mTitleList.get(position);
        }
    }



    @Override
    public void onStatucChanged(SlideDetailsLayout.Status status) {

    }


    private void getGoodsDetailBase(FastBuyGoodsDetailResponseBean.DataBean data) {
        if (goodsDetailData == null) {
            goodsDetailData = new GoodsDetailBaseResponseBean.DataBean();
        }

        goodsDetailData.setImg_thumb_min(data.getImg_thumb_min());
        goodsDetailData.setGoods_name(data.getGoods_name());
        goodsDetailData.setBrand_name(data.getBrand_name());
        goodsDetailData.setSub_name(data.getSub_name());
        goodsDetailData.setStock(data.getStock());
        goodsDetailData.setSale_limit(data.getSale_limit());
        goodsDetailData.setPrice(data.getPrice());
        goodsDetailData.setEvent_price(data.getEvent_price());
        goodsDetailData.setCart_num(data.getCart_num());
        goodsDetailData.setBrand_size(data.getBrand_size());


        ViewUtils.getView(activity, R.id.ll_nav_bottom).setClickable(true);
    }

    private void displayGoodsDetail(FastBuyGoodsDetailResponseBean.DataBean data) {
        if (data.getIs_collect() == 1) {
            ivIclike.setImageResource(R.drawable.ic_loved);
        } else {
            ivIclike.setImageResource(R.drawable.ic_love);
        }

        if (!ViewUtils.isEmpty(data.getCart_num()) && !"0".equals(data.getCart_num())) {
            tv_bag_count.setVisibility(View.VISIBLE);
            tv_bag_count.setText(data.getCart_num());
        } else tv_bag_count.setVisibility(View.GONE);

        if (!TextUtils.isEmpty(data.getSub_name())) {
            tvTitlefirst.setText(data.getSub_name());
        }
        if (!TextUtils.isEmpty(data.getGoods_name())) {
            tvTitlesecond.setText(data.getGoods_name());
        }
        if (!TextUtils.isEmpty(data.getPrice())) {
            tvTotal.setText("¥ " + data.getPrice());
        }
        if(!TextUtils.isEmpty(data.getPrice())&&!TextUtils.isEmpty(data.getMarket_price())&& !data.getMarket_price().equals(data.getPrice())) {
                tvMarketPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                tvMarketPrice.setText("¥ "+data.getMarket_price());
        }else{
            tvMarketPrice.setVisibility(View.GONE);
        }

        if (!TextUtils.isEmpty(data.getCycle())) {
            tvNeedtime.setText("生产周期:"+data.getCycle());
        }

        if(!TextUtils.isEmpty(data.getBarcode())){
            tv_barcode.setText(data.getBarcode());
            tv_barcode.setVisibility(View.VISIBLE);
        }else {
            tv_barcode.setVisibility(View.GONE);
        }

        ll_pull_up.setVisibility(View.VISIBLE);


    }

    private void goodsCollect() {
        GoodsCollectRequestFilter filter = new GoodsCollectRequestFilter(activity);
        filter.requestBean.method = goodsDetail.getData().getIs_collect() == 0 ? "goodsCollect" : "goodsUnCollect";
        filter.requestBean.goods_id = goodsDetail.getData().getId();
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<BaseResponseBean>() {
            @Override
            public void onSuccess(BaseResponseBean result) {
                goodsDetail.getData().setIs_collect(0 == goodsDetail.getData().getIs_collect() ? 1 : 0);
                if (goodsDetail.getData().getIs_collect() == 1) {
                    ivIclike.setImageResource(R.drawable.ic_loved);
                } else {
                    ivIclike.setImageResource(R.drawable.ic_love);
                }
            }
            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                if (failedType != 300)
                    ToastUtils.showToast("操作失败");
            }
        });
    }

    @OnClick(R.id.tv_addCart)
    public void clickAddCart(){
        navIndex = 0;
        initDialog();
    }


    //加入购物车
    private void joinCart() {
        final JoinCartRequestFilter filter = new JoinCartRequestFilter(activity);
        filter.requestBean.gid = product_id;
        filter.requestBean.is_pay = navIndex == 0 ? 0 : 1;
        filter.requestBean.zg_flag = 1;
        filter.requestBean.number = String.valueOf(count);
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<BaseResponseBean>() {
            @Override
            public void onSuccess(BaseResponseBean result) {
                if (navIndex == 0) {
                    if (ViewUtils.isEmpty(goodsDetailData.getCart_num()) || "0".equals(goodsDetailData.getCart_num())) {
                        goodsDetailData.setCart_num("1");
                    } else {
                        goodsDetailData.setCart_num(String.valueOf(Integer.parseInt(goodsDetailData.getCart_num()) + 1));
                    }
                    tv_bag_count.setVisibility(View.VISIBLE);
                    tv_bag_count.setText(goodsDetailData.getCart_num());

                    ToastUtils.showToast("加入购物车成功");
                } else if (navIndex == 1) {
                    Intent intent = new Intent(activity, OrderFormActivity.class);
                    intent.putExtra("type",3);
                    startActivity(intent);
                }

                if (buyDialog != null && buyDialog.isShowing()) buyDialog.hide();
            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                ToastUtils.showToast(navIndex == 0 ? "加入购物车失败" : (!ViewUtils.isEmpty(serverError.mess) ? serverError.mess : "网络连接不稳定，请稍后再试"));
            }
        });
    }

    String product_id;

    /**
     * buy dialog
     */
    Dialog buyDialog;
    View view;
    ImageView iv_buy_image, iv_minus, iv_plus;
    TextView tv_count, tv_buy_name, tv_brandname, tv_to_pay, tv_pay;
    LinearLayout ll_content;

    int count = 0, storeCount = 0;
    /**
     * 单价
     */
    Double price;

    FastGoodsDetailUtils goodsDetailUtils;
    TabLayout mTabLayout;
    BanViewPager mViewPager;
    private void initDialog() {

        if (buyDialog == null && goodsDetailData != null) {
            view = LayoutInflater.from(this).inflate(R.layout.dialog_fastbuy, null);
            view.setMinimumWidth(getResources().getDisplayMetrics().widthPixels);
            ViewUtils.getView(view, R.id.iv_cancel).setOnClickListener(this);
            ViewUtils.getView(view, R.id.iv_minus).setOnClickListener(this);
            ViewUtils.getView(view, R.id.iv_plus).setOnClickListener(this);
            ViewUtils.getView(view, R.id.tv_pay).setOnClickListener(this);
            dialog_web_size = ViewUtils.getView(view, R.id.web_size);
            iv_buy_image = ViewUtils.getView(view, R.id.iv_buy_image);
            tv_buy_name = ViewUtils.getView(view, R.id.tv_name);
            tv_brandname = ViewUtils.getView(view,R.id.tv_sub);
            tv_to_pay = ViewUtils.getView(view, R.id.tv_topay);
            iv_minus = ViewUtils.getView(view, R.id.iv_minus);
            iv_plus = ViewUtils.getView(view, R.id.iv_plus);
            tv_count = ViewUtils.getView(view, R.id.tv_count);
            ll_content = ViewUtils.getView(view, R.id.ll_selector);
            tv_pay = (TextView) view.findViewById(R.id.tv_pay);

            displayGoodsDetailBase();

            goodsDetailUtils = new FastGoodsDetailUtils(FastGoodsDetailActivity.this);
            goodsDetailUtils.reloadDatas(activity, goodsDetail, ll_content, new FastGoodsDetailUtils.OnSelectedListener() {
                @Override
                public void onBaseDatasChanged(GoodsDetailBaseResponseBean.DataBean baseResponseBean) {

                    goodsDetailData = baseResponseBean;
                    displayGoodsDetailBase();
                }
            });

            buyDialog = new Dialog(activity, R.style.BuyDialogStyle);
            buyDialog.setContentView(view);
            Window dialogWindow = buyDialog.getWindow();
            dialogWindow.setGravity(Gravity.BOTTOM);
            WindowManager.LayoutParams params = dialogWindow.getAttributes();
            params.x = 0;
            params.y = 0;
            dialogWindow.setAttributes(params);
        }

        if (TextUtils.equals(goodsDetail.getData().getIs_license(), "0") && App.user != null && App.user.getUserType() != 1) {
            tv_pay.setBackgroundColor(getResources().getColor(R.color.text_introduce));
            tv_pay.setText("该商品仅实体店出售");
            tv_pay.setClickable(false);

        } else {

            if (navIndex == 0) {
                tv_pay.setText("确定");
            } else if (navIndex == 1) {
                tv_pay.setText("去付款");
            }
        }

        buyDialog.show();
    }


    private void displayGoodsDetailBase() {
        if (!ViewUtils.isEmpty(goodsDetailData.getImg_thumb_min()))
            XUtils.image(iv_buy_image, goodsDetailData.getImg_thumb_min());
        if(!ViewUtils.isEmpty(goodsDetailData.getSub_name())){
            tv_brandname.setText(goodsDetailData.getSub_name());
        }
        if (!ViewUtils.isEmpty(goodsDetailData.getGoods_name()))
            tv_buy_name.setText(goodsDetailData.getGoods_name());
//        if (!ViewUtils.isEmpty(goodsDetailData.getPrice()))
//            tv_buy_price.setText("总价¥ " + goodsDetailData.getPrice());
        if(!ViewUtils.isEmpty(goodsDetailData.getEvent_price())){
            tv_to_pay.setText("¥ " + goodsDetailData.getPrice());
        }
        if (!ViewUtils.isEmpty(goodsDetailData.getStock())) {
//            tv_buy_stock.setText("库存 " + goodsDetailData.getStock() + "件 ");
            LogUtil.d("st=" + goodsDetailData.getStock());
            LogUtil.d("st=" + goodsDetailData.getSale_limit());
            if (TextUtils.equals("0", goodsDetailData.getSale_limit()))
                storeCount = Integer.parseInt(goodsDetailData.getStock());
            else
                storeCount = Math.min(Integer.parseInt(goodsDetailData.getStock()), Integer.parseInt(goodsDetailData.getSale_limit()));
        }
        if (!ViewUtils.isEmpty(goodsDetailData.getBrand_size())) {
            dialog_web_size.getSettings().setJavaScriptEnabled(true);
            dialog_web_size.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
            dialog_web_size.setWebChromeClient(new WebChromeClient());
            dialog_web_size.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
            dialog_web_size.loadDataWithBaseURL(null, goodsDetailData.getBrand_size(), "text/html", "utf-8", null);
            dialog_web_size.scrollTo(0, 0);
        }

        if (storeCount > 0)
            count = 1;
        else count = 0;
        price = Double.parseDouble(goodsDetailData.getPrice());

        displayBuyCountAndPrice();
    }

    private void displayBuyCountAndPrice() {
        tv_count.setText(String.valueOf(count));
        if (count > 1) iv_minus.setImageResource(R.drawable.minus);
        else iv_minus.setImageResource(R.drawable.minus_grey);
        if (count >= storeCount) iv_plus.setImageResource(R.drawable.plus_grey);
        else iv_plus.setImageResource(R.drawable.plus);
    }

    private int nowIndex;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);


    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_share:
                showShare();
                break;
            case R.id.iv_iclike:
                /** collection */
                if (App.user != null && !App.user.getLoginState()) {
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.putExtra("type","like");
                    startActivity(intent);
                    return;
                }
                goodsCollect();
                break;
            case R.id.rl_shopping_bag:
                /** to shopping bag */
                startActivity(new Intent(activity, ShoppingCartActivity.class));
                break;
            case R.id.iv_service:
                /** start conversation to service */
                if (App.user != null && !App.user.getLoginState()) {
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.putExtra("type","service");
                    startActivity(intent);
                    return;
                }
                startActivity(new Intent(this, com.easemob.helpdeskdemo.ui.LoginActivity.class).putExtra(Constant.MESSAGE_TO_INTENT_EXTRA,
                        Constant.MESSAGE_TO_PRE_SALES));
                break;
            case R.id.tv_gopay:
                if (App.user != null && !App.user.getLoginState()) {
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.putExtra("type","pay");
                    startActivity(intent);
                    return;
                }
                //即将开始
                if(event_type == 1){
                    tvGopay.setClickable(false);
                }else if(event_type == 0){
                    goToNotice();
                }else {
                    navIndex = 1;
                    initDialog();
                }
                break;
            case R.id.iv_cancel:
                buyDialog.hide();
                break;
            case R.id.iv_minus:
                if (count > 1) {
                    count--;
                    displayBuyCountAndPrice();
                }
                break;
            case R.id.iv_plus:
                if (count < storeCount) {
                    count++;
                    displayBuyCountAndPrice();
                }
                break;
            case R.id.tv_pay:
                if (TextUtils.isEmpty(goodsDetailUtils.getGoods_id()) || goodsDetailUtils.getGoods_id() == null) {
                    return;
                }
                product_id = goodsDetailUtils.getGoods_id();

                if (count < 1 || count > storeCount || storeCount < 1) {
                    ToastUtils.showToast("暂无库存，尽情期待");
                    return;
                }
                product_id = goodsDetailUtils.getGoods_id();

                //跳转到订单见面
                buyDialog.hide();
                joinCart();
                break;

            case R.id.ll_pull_up:
                //上拉查看图文详情
                sv_switch.smoothOpen(true);
                break;
            case R.id.tv_complete:
                dialog_info.dismiss();
                break;

        }
    }

    private void goToNotice() {
        FastBuyNoticeRequestFilter filter = new FastBuyNoticeRequestFilter(activity);
        if(TextUtils.isEmpty(notice_id)){
            return;
        }
        filter.requestBean.goods_id = Integer.parseInt(notice_id);
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<BaseResponseBean>() {
            @Override
            public void onSuccess(BaseResponseBean result) {
                ToastUtils.showToast(result.getMessage().toString());
            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                ToastUtils.showToast(serverError.mess);
            }
        });
    }

    @OnClick(R.id.tv_scan)
    public void Scan(){
        if(tv_scan.getText().equals("申请上架")){
            applySale();
            return;
        }else{
            finish();
        }
    }

    private void applySale() {
        if(TextUtils.isEmpty(gdid)){
            ToastUtils.showToast("请稍后再试");
            return;
        }
        ApplyShelfRequestFilter filter = new ApplyShelfRequestFilter(activity);
        filter.requestbean.goods_id = gdid;
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<BaseResponseBean>() {
            @Override
            public void onSuccess(BaseResponseBean result) {
                ToastUtils.showToast(result.getMessage()+"");
                tv_scan.setClickable(false);
                tv_scan.setText("已申请上架");
                tv_scan.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_button_press));
            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                ToastUtils.showToast(serverError.mess);
            }
        });
    }


    @OnClick(R.id.ll_product)
    public void goToproduct(){
        if(!TextUtils.isEmpty(h5_url)) {
            Intent intent = new Intent(this, WebViewActivity.class);
            intent.putExtra("url", h5_url);
            startActivity(intent);
        }
    }
    public class DialogAdapter extends BaseAdapter
    {

        @Override
        public int getCount() {

            return tips.size();
        }
        @Override
        public Object getItem(int position) {

            return position;
        }
        @Override
        public long getItemId(int position) {

            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;

            if(convertView == null)
            {
                holder = new ViewHolder();
                convertView = getLayoutInflater().from(FastGoodsDetailActivity.this).inflate(R.layout.item_dialoginfo, null);
                holder.title = (TextView)convertView.findViewById(R.id.tv_title);
                holder.name = (TextView)convertView.findViewById(R.id.tv_name);
                holder.desc = (TextView)convertView.findViewById(R.id.tv_desc);
                convertView.setTag(holder);
            }else
            {
                holder = (ViewHolder)convertView.getTag();
            }
            holder.title.setText(tips.get(position).getName().substring(0,2));
            holder.name.setText(tips.get(position).getName());
            holder.desc.setText(tips.get(position).getDesc());
            return convertView;
        }

        //ViewHolder静态类
        class ViewHolder
        {
            public TextView title,name;
            public TextView desc;
        }

    }

    private class CropSquareTransformation implements Transformation {
        @Override
        public Bitmap transform(Bitmap source) {

            int targetWidth = getWindowManager().getDefaultDisplay().getWidth();

            int targetHeight = source.getHeight();

            if (source.getWidth() == 0 || source.getHeight() == 0) {
                return source;
            }

            if (source.getWidth() >=source.getHeight()) {//横向长图
                //
                if (source.getWidth() < targetWidth ) {
                    double aspectRatio = (double) source.getWidth() / (double) source.getHeight();
                    int height = (int) (targetWidth / aspectRatio);
                    return source;
                } else {
                    //如果图片大小大于等于设置的高度，则按照设置的高度比例来缩放
                    double aspectRatio = (double) source.getWidth() / (double) source.getHeight();
                    int height = (int) (targetWidth / aspectRatio);
//                    if (width > 400) { //对横向长图的宽度 进行二次限制
//                        width = 400;
//                        targetHeight = (int) (width / aspectRatio);// 根据二次限制的宽度，计算最终高度
//                    }
                    if (height != 0 && targetHeight != 0) {
                        Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
                        if (result != source) {
                            // Same bitmap is returned if sizes are the same
                            source.recycle();
                        }
                        return result;
                    } else {
                        return source;
                    }
                }
            } else {//竖向长图
                //如果图片小于设置的宽度，则返回原图
                if (source.getWidth() <=targetWidth) {
                    return source;
                } else {
                    //如果图片大小大于等于设置的宽度，则按照设置的宽度比例来缩放
                    double aspectRatio = (double) source.getHeight() / (double) source.getWidth();
                    int height = (int) (targetWidth * aspectRatio);
//                    if (height > 600) {//对横向长图的高度进行二次限制
//                        height = 600;
//                        targetWidth = (int) (height / aspectRatio);//根据二次限制的高度，计算最终宽度
//                    }
                    if (height != 0 && targetWidth != 0) {
                        Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, height, false);
                        if (result != source) {
                            // Same bitmap is returned if sizes are the same
                            source.recycle();
                        }
                        return result;
                    } else {
                        return source;
                    }
                }
            }
        }

        @Override
        public String key() {
            return "desiredWidth" + " desiredHeight";
        }
    }

}
